﻿using System;
using System.Text;
using System.IO;
using WoltersKluwer.SPChainGang.Core.Constants;

namespace WoltersKluwer.SPChainGang.Core.Util
{
    public static class CSVReportHelper
    {
        public static string CSV_SEPARATOR = ",";
        public static string DOUBLE_QUOTES = "\"";
        public static string CSV_DOUBLE_QUOTES = "\"\"";

        public static void AppendRow(string file, string origin, string detected, string replacement, string additionalInfo,string timeStamp)
        {
            string csvRow = GenerateRowString(origin, detected, replacement, additionalInfo, timeStamp);
            File.AppendAllText(file, csvRow);
            return;
        }

        public static void AppendRow(string file, string origin, string detected, string replacement, string additionalInfo)
        {
             AppendRow(file, origin, detected, replacement, additionalInfo, DateTime.Now.ToString(GlobalConstants.TimeStampPattern));
             return;
        }

        //TODO: WTF? need a flexible function accepting params string[]
        private static string GenerateRowString(string origin, string detected, string replacement, string additionalInfo,string dateTimeStamp)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(CheckCSVCell(dateTimeStamp));
            sb.Append(CSV_SEPARATOR);
            sb.Append(CheckCSVCell(origin));
            sb.Append(CSV_SEPARATOR);
            sb.Append(CheckCSVCell(detected));
            sb.Append(CSV_SEPARATOR);
            sb.Append(CheckCSVCell(replacement));
            sb.Append(CSV_SEPARATOR);
            sb.Append(CheckCSVCell(additionalInfo));
            sb.Append(Environment.NewLine);
            return sb.ToString();
        }

        private static string CheckCSVCell(string cellText)
        {
            if(string.IsNullOrEmpty(cellText))
            {
                return string.Empty;
            }
            if (cellText.Contains(CSV_SEPARATOR) || cellText.Contains(CSV_DOUBLE_QUOTES))
            {
                cellText.Replace(DOUBLE_QUOTES, CSV_DOUBLE_QUOTES);
                cellText = string.Concat(DOUBLE_QUOTES, cellText, DOUBLE_QUOTES);
            }
            return cellText;
        }
    }
}
